const Router = require('koa-router');
const query = require('../util/mysql');
const wrapper = require('../util/wrapper');
const checkError = require('../util/checkError');
const R = require('ramda/src');
const moment = require('moment-mini');

const router = new Router();

router.prefix('/api/article');

module.exports = router;

/**
 * 获取所有文章
 */
router.get('/all', async (ctx, next) => {
  let res = await query('select a.*,c.name as cname from article a left join category c on a.cid=c.id order by create_time desc');
  if (checkError(res)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }

  res = R.map(item => {
    item['create_time'] = moment(+item['create_time']).format('YYYY-MM-DD HH:mm:ss');
    return item;
  })(res);

  ctx.body = await wrapper(res);
});

/**
 * 获取热点文章列表
 */
router.get('/category/hot', async (ctx, next) => {
  const hot = await query(`select h.*,c.name from category_hot h left join category c on h.cid=c.id`);

  for (let i = 0, len = hot.length; i < len; i++) {
    const articles = await query(`select * from article where cid=${hot[i].cid} limit 5`);
    hot[i]['list'] = articles;
  }

  ctx.body = await wrapper(hot);
});

/**
 * 获取指定id文章
 */
router.get('/:id', async (ctx, next) => {
  const id = ctx.params.id;
  if (!id) {
    ctx.body = await wrapper(new Error('参数有误.'));
    return false;
  }
  let res = await query(`select * from article where id=${id}`);
  if (checkError(res)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }

  res = R.map(item => {
    item['create_time'] = moment(+item['create_time']).format('YYYY-MM-DD HH:mm');
    return item;
  })(res);

  ctx.body = await wrapper(res[0]);
});

/**
 * 获取指定栏目的所有文章
 */
router.get('/category/:cid', async (ctx, next) => {
  const cid = ctx.params.cid;
  const { subMenuIds, orderby = 'create_time desc' } = ctx.query;
  const { pageNo = 1, pageSize = 10 } = ctx.query;
  if (!cid) {
    ctx.body = await wrapper(new Error('参数有误.'));
    return false;
  }

  const ids = subMenuIds ? `${cid},${subMenuIds}` : cid;
  let res = await query(`select id,cid,title,create_time,top,(SELECT COUNT(*) FROM article where cid in (${ids})) as total from article where cid in (${ids}) order by top desc,${orderby} limit ${pageSize} offset ${pageNo - 1}`);
  if (checkError(res)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }

  const obj = {
    total: res.length > 0 ? res[0].total : 0,
    pageNo,
    pageSize,
  };

  res = R.compose(
    R.map(R.pick(['id', 'cid', 'title', 'create_time', 'top'])),
    R.map(item => {
      item['create_time'] = moment(+item['create_time']).format('YYYY-MM-DD');
      return item;
    })
  )(res);

  obj['data'] = res;

  ctx.body = await wrapper(obj);
});

/**
 * 修改/新增文章
 */
router.post('/edit', async (ctx, next) => {
  const { id, cid, title, content,top = 0 } = ctx.request.body;
  if (!title || !content || title && content && !id && !cid) {
    ctx.body = await wrapper(new Error('参数有误.'));
    return false;
  }
  console.log(id, cid, title, content,top);
  let res;
  if (id) {
    res = await query(`update article set cid='${cid}',title='${title}',content='${content}',top='${top}' where id=${id}`);
  } else {
    res = await query(`insert into article(cid,title,content,top,create_time) values('${cid}','${title}','${content}','${top}','${Date.now()}')`);
  }
  if (checkError(res)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }
  ctx.body = await wrapper(id ? '修改成功' : '新增成功');
});

/**
 * 删除文章
 */
router.post('/del', async (ctx, next) => {
  const { id } = ctx.request.body;
  if (!id) {
    ctx.body = await wrapper(new Error('参数有误.'));
    return false;
  }
  const res = await query(`delete from article where id=${id}`);
  if (checkError(res)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }
  ctx.body = await wrapper('删除成功');
});
